package com.gd.deron.smartrobot.baobao.service;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.gd.deron.smartrobot.baobao.R;
import com.gd.deron.smartrobot.baobao.iml.WakeListener;
import com.gd.deron.smartrobot.baobao.utils.BlueTools;
import com.gd.deron.smartrobot.baobao.utils.Config;
import com.gd.deron.smartrobot.baobao.utils.InstructionUtil;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.VoiceWakeuper;
import com.iflytek.cloud.WakeuperListener;
import com.iflytek.cloud.WakeuperResult;
import com.iflytek.cloud.util.ResourceUtil;
import com.iflytek.cloud.util.ResourceUtil.RESOURCE_TYPE;

public class WakeService extends Service {

	public static VoiceWakeuper wakeObject;
	private int curThresh = -20;

	public static boolean isWake = true;
	private static WakeService mWakeXunFeiService;
	private WakeListener mWakeListener;

	@Override
	public void onCreate() {
		initWake();
		super.onCreate();

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		startWakeAiJia();

		Log.i("onStartCommand", "onStartCommand");
		return super.onStartCommand(intent, flags, startId);

	}

	private void initWake() {

		// 加载唤醒资源
		StringBuffer buffer = new StringBuffer();
		String resPath = ResourceUtil.generateResourcePath(WakeService.this, RESOURCE_TYPE.assets,
				"ivw/" + getString(R.string.app_id) + ".jet");
		// Log.d("resPath", resPath);

		buffer.append(SpeechConstant.IVW_RES_PATH + "=" + resPath);
		buffer.append("," + ResourceUtil.ENGINE_START + "=" + SpeechConstant.ENG_IVW);
		Log.i("buffer.toString()", buffer.toString());
		boolean ret = SpeechUtility.getUtility().setParameter(ResourceUtil.ENGINE_START, buffer.toString());
		if (!ret) {
			Log.d("MainActivity", "启动本地引擎失败！");
			return;
		}

		// 初始化唤醒对象
		wakeObject = VoiceWakeuper.createWakeuper(this, null);
		// 清空参数
		wakeObject.setParameter(SpeechConstant.PARAMS, null);
		wakeObject.setParameter(SpeechConstant.IVW_THRESHOLD, "0:" + curThresh);
		// 唤醒模式
		wakeObject.setParameter(SpeechConstant.IVW_SST, "wakeup");
		// 设置持续进行唤醒
		wakeObject.setParameter(SpeechConstant.KEEP_ALIVE, "1");
	}

	/**
	 * 开始唤醒
	 */
	public void startWakeAiJia() {

		if (wakeObject != null) {
			if (!wakeObject.isListening()) {
				// 开始唤醒
				wakeObject.startListening(mWakeuperListener);
			}
		} else {
			showToastTip("wake not init");
		}
	}

	public boolean isWake() {
		if (wakeObject != null) {
			return wakeObject.isListening();

		} else {
			return false;
		}
	}

	/**
	 * 停止唤醒
	 */
	public  void stopWakeAiJia() {
		// wakeObject = VoiceWakeuper.getWakeuper();
		if (wakeObject != null) {
			if (wakeObject.isListening()) {
				wakeObject.stopListening();
				wakeObject.cancel();
			}

		} else {
			// showToastTip("wake not init");
		}

	}

	/**
	 * 听写监听
	 */
	private WakeuperListener mWakeuperListener = new WakeuperListener() {

		@Override
		public void onBeginOfSpeech() {
			Log.i("onBeginOfSpeech", "开始");
			// showToastTip("开始");
		}

		@Override
		public void onError(SpeechError arg0) {
			Log.e("onError", "错误" + arg0);
			showToastTip("wake error:" + arg0);
		}

		@Override
		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
			Log.i("onEvent", "事件");
			showToastTip("onEvent");
		}

		@Override
		public void onResult(WakeuperResult result) {

			try {
				String text = result.getResultString();
				JSONObject object;
				object = new JSONObject(text);
				int num = object.optInt("id");
				// showToastTip("唤醒了"+"id:"+num);
				int score = Integer.parseInt(object.optString("score"));
				Log.i("score", score + "" + ">" + "num=" + num);
				if (score > 10) {
					switch (num) {

					case 0:// 醒醒//在线语音互动 需要解决远程监控录音占用问题
						broadcastSend(Config.AIJIA_XINGXING);
						break;
					case 1:// 哈喽爱佳
						broadcastSend(Config.AIJIA_HELLO);
						break;
					case 2:// 爱佳你好
						broadcastSend(Config.AIJIA_NIHAO);
						break;

					default:
						break;
					}

				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		@Override
		public void onVolumeChanged(int arg0) {
			BlueTools.sendData(InstructionUtil.LIGTH_LEFT_RIGHT_ONLY_ONE);
		}

	};

	private void broadcastSend(final String action) {
		final Intent mIntent = new Intent();
		// mIntent.setAction("asr.online.startunderstand");
		mIntent.setAction(action);
		sendBroadcast(mIntent);
	}

	/**
	 * 显示
	 */
	private void showToastTip(String str) {
		Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
	}

	private MyBinder myBinder = new MyBinder();

	@Override
	public IBinder onBind(Intent intent) {

		// return myBinder;
		return myBinder;
	}

	public class MyBinder extends Binder {
		public WakeService myService() {
			return WakeService.this;
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		stopWakeAiJia();
	}

}
